JavaScript is partly an object-oriented language.
To learn JavaScript, we got to learn the object-oriented parts of JavaScript.
In this article, we’ll look at boolean, comparisons, and new primitive types which are the building blocks of objects.
Lazy Evaluation
Booleans expressions are lazily evaluated.
This means that it evaluates the expression until the result is clear.
So if we have:
true || "foo";
then the JavaScript engine stops at true
and returns that because it’s clearly true
no matter what the 2nd operand is.
However, if we have:
true && "foo";
then both are evaluated and the 2nd operand is returned.
We can use this behavior to let us initialize variables to a default value.
For instance, we can write:
let num = num || 10;
If num
is falsy, then num
will be assigned 10.
Comparison
Comparison operators also return boolean values.
There are the ==
and ===
operators for equality comparisons.
And !=
and !==
for inequality comparisons.
>
returns true
if the left operand is greater than the right operand.
And >=
returns true
if the left operand is greater than or equal to the right operand.
<
returns true
if the right operand is greater than the left operand.
And <=
returns true
if the right operand is greater than or equal to the left operand.
We should use ===
and !==
for equality and inequality comparisons since they don’t cast the operands before comparing them.
Undefined and null
undefined
means a value doesn’t exist.
If we have an uninitialized variable, then the it’s undefined
.
So if we have:
let x
then x
is undefined
.
typeof x
would returns 'undefined'
.
null
isn’t assigned by JavaScript behind the scenes, it’s assigned by our code.
So if we have:
let y = null
then y
is null
.
typeof y
would be 'object'
since it’s null
.
They can be converted to a boolean or a string.
For instance, we can write:
!!undefined;
or
!!null;
they both return false
since they’re both falsy.
We can write:
"value: " + null;
"value: " + undefined;
And we get:
"value: null"
and
"value: undefined"
Symbols
Symbols are a new primitive type.
These are used as unique identifiers.
We create a symbol by using the Symbol
function.
For instance, we can write:
const atom = Symbol();
We don’t use the new
keyword since Symbol
isn’t a constructor.
We can pass in a string into it:
const bar = Symbol('bar')
No 2 symbols are the same.
So if we have:
console.log(Symbol('bar') === Symbol('bar'))
or:
console.log(Symbol() === Symbol())
they’re both false
.
Bigint
Bigint is another primitive type.
They are integers with an n
suffix.
We can write like:
10n
We can do arithmetic with 2 bigints.
So we can write:
10n * 2n
and get 20n
.
They can be outside of the safe range of JavaScript integers, which is -2 ** 53
and 2 ** 53
, so we can use them to represent any integer.
Conclusion
Booleans are lazily evaluated.
undefined
represents non-existing value.
null
represents no value.
Symbols are used as unique identifi8ers.
Bigints are large integers that can be anything.